<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="计划名称" v-bind="validateInfos.planName">
            <a-input v-model:value="formData.planName" placeholder="请输入计划名称"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="平台" v-bind="validateInfos.platform">
            <j-dict-select-tag
              v-model:value="formData.platform"
              dictCode="platform"
              placeholder="请选择平台"
              :disabled="disabled"
              :showChooseOption="false"
              :isShowAll="false"
              :noShowList="['0', '3']"
              :currMenu="'appVersion'"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="图片" v-bind="validateInfos.img">
            <j-image-upload v-model:value="formData.img" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="内容类型" v-bind="validateInfos.contentType">
            <a-select
              v-model:value="formData.contentType"
              placeholder="请选择内容类型"
              :disabled="disabled"
            >
              <a-select-option :value="1">小说</a-select-option>
              <a-select-option :value="2">H5页面</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="内容" v-bind="validateInfos.content">
            <a-input v-model:value="formData.content" placeholder="请输入内容"
                     :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="触发方式" v-bind="validateInfos.triggerType">
            <a-radio-group v-model:value="formData.triggerType">
              <a-radio :value="1">冷启动首页</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="展示频率" v-bind="validateInfos.frequencyCountRadio">
            <a-radio-group v-model:value="formData.frequencyCountRadio" class="frequency"
                           @change="radioChange">
              <a-radio :value="-1">不限制</a-radio>
              <div class="frequency-1">
                <a-radio :value="1" class="frequency-2">
                  <span>每</span>
                </a-radio>
                <div class="frequency-3">
                  <a-form-item v-bind="validateInfos.frequencyInterval">
                    <a-input-number v-model:value="formData.frequencyInterval"
                                    placeholder=""
                                    style="width: 100%"
                                    name="frequencyInterval"
                                    :disabled="disabled||formData.frequencyCountRadio===-1"/>
                  </a-form-item>
                  <a-form-item v-bind="validateInfos.frequencyType" name="frequencyType" class="frequency-select-item">
                    <a-select
                      v-model:value="formData.frequencyType"
                      class="frequency-select"
                      :disabled="disabled||formData.frequencyCountRadio===-1"
                    >
                      <a-select-option :value="1">天</a-select-option>
                      <a-select-option :value="7">周</a-select-option>
                      <a-select-option :value="30">月</a-select-option>
                    </a-select>
                  </a-form-item>
                  <p class="font-p">展示</p>
                  <a-form-item v-bind="validateInfos.frequencyCount" name="frequencyCount">
                    <a-input-number v-model:value="formData.frequencyCount" placeholder=""
                                    style="width: 100%"
                                    :disabled="disabled||formData.frequencyCountRadio===-1"/>
                  </a-form-item>
                  <p class="font-p">次</p>
                </div>
              </div>

            </a-radio-group>

          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="有效日期" v-bind="validateInfos.time">
            <a-range-picker
              v-model:value="formData.time"
              :disabled="disabled"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted} from 'vue';
  import {defHttp} from '/@/utils/http/axios';
  import {useMessage} from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import {getValueType} from '/@/utils';
  import {saveOrUpdate} from '../AppPopWindowPlan.api';
  import {Form} from 'ant-design-vue';
  import dayjs, {Dayjs} from 'dayjs';

  const props = defineProps({
    formDisabled: {type: Boolean, default: false},
    isCopy: {type: Boolean, default: false},
    formData: {
      type: Object, default: () => {
      }
    },
    formBpm: {type: Boolean, default: true}
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    planName: '',
    platform: '',
    contentType: undefined,
    content: '',
    img: '',
    time: [],
    triggerType: 1,
    frequencyType: '',
    frequencyInterval: undefined,
    frequencyCountRadio: -1,
    frequencyCount: undefined,
  });
  const {createMessage} = useMessage();
  const labelCol = ref<any>({xs: {span: 24}, sm: {span: 5}});
  const wrapperCol = ref<any>({xs: {span: 24}, sm: {span: 16}});
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    platform: [{required: true, message: '请选择平台!'},],
    planName: [{required: true, message: '请输入计划名称!'},],
    img: [{required: true, message: '请选择图片!'},],
    contentType: [{required: true, message: '请选择内容类型!'},],
    content: [{required: true, message: '请输入内容!'},],
    triggerType: [{required: true, message: '请选择触发方式!'},],
    frequencyCountRadio: [{required: true, message: '请选择展示频率!'},],
    time: [{required: true, message: '请选择有效日期!',trigger: 'change'},],
    frequencyInterval: [{required: true, message: '请输入间隔!'},],
    frequencyType: [{required: true, message: '请选择单位!'},],
    frequencyCount: [{required: true, message: '请输入次数!'},],
  };
  const {resetFields, validate, validateInfos,clearValidate} = useForm(formData, validatorRules, {immediate: true});

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  const disabledDate = (current: Dayjs) => {
    return current && current < dayjs().subtract(1, 'day').endOf('day');
  };

  function radioChange() {
    if (formData.frequencyCountRadio === -1) {
      formData.frequencyInterval = undefined
      formData.frequencyCount = undefined
      formData.frequencyType = ''
      setTimeout(()=>{
        clearValidate(['frequencyInterval','frequencyCount','frequencyType'])
      },100)

    }
  }


  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    let res
    if (record.id) {
      res = dealEditData(record)
      if (props.isCopy) {
        res.id = ''
      }
    } else {
      res = record
    }
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, res);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    let arr=[
      'platform',
      'planName',
      'img',
      'contentType',
      'content',
      'triggerType',
      'frequencyCountRadio',
      'time',
    ]
    if (formData.frequencyCountRadio===1){
      arr=[...arr,'frequencyInterval','frequencyType','frequencyCount']
    }
    // 触发表单验证
    await validate(arr);
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = JSON.parse(JSON.stringify(formData));
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    model = dealPushData(model)
    console.log(model)
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  /**
   * 处理提交数据
   * @param model
   */
  function dealPushData(model) {
    let cloneObj = JSON.parse(JSON.stringify(model))
    let timeArr = cloneObj.time.split(',')
    cloneObj.startTime = timeArr[0]
    cloneObj.endTime = timeArr[1]
    if (cloneObj.frequencyCountRadio === -1) {
      cloneObj.frequencyType = -1
    }
    return cloneObj
  }

  /**
   * 处理编辑数据
   * @param model
   */
  function dealEditData(record) {
    let cloneRecord = JSON.parse(JSON.stringify(record))
    let startTime = cloneRecord.startTime
    let endTime = cloneRecord.endTime
    cloneRecord.time = [startTime, endTime]
    if (cloneRecord.frequencyType === -1) {
      cloneRecord.frequencyCountRadio = -1
      cloneRecord.frequencyType = ''
    } else {
      cloneRecord.frequencyCountRadio = 1
    }
    console.log(cloneRecord, 'zzxxcc')
    return cloneRecord
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }

  .frequency {
    width: 100%;
    p{
      font-size: 14px;
      margin-bottom: 0;
      margin: 8px;
    }
    .frequency-1 {
      display: flex;
      align-items: center;

      .frequency-3 {
        display: flex;
        align-items: center;
        width: 100%;

        /deep/.ant-form-item{
          margin-bottom: 0;
          height: 30px;
        }
        /deep/.frequency-select{
          width: 120px;
          margin-left: 12px;
        }
        /deep/.frequency-select-item{
          .ant-form-item-explain-error{
            left: 12px;
          }
        }

        /deep/.ant-form-item-explain-error{
          position: absolute;
        }
      }
    }
  }
</style>
